<script setup>
import { onMounted, reactive, ref } from "vue";
import axios from "axios";
import { Plus, Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router"; // 更规范的引入方式

const router = useRouter();

const url = 'http://localhost:8080/file/downLoad?fileName=';

// 状态管理
const saveOrUpdateVisible = ref(false);
const saveOrUpdateTitle = ref('');
const total = ref(0);
const tableData = ref([]);
const delLoading = ref(false); // 删除加载状态

// 查询表单（使用 reactive 管理复杂对象）
const formInline = reactive({
  pageNum: 1,
  pageSize: 5,
  title: '',
});

// 生命周期钩子
onMounted(() => {
  getList();
});

/**
 * 跳转到回复页面
 * @param {number} id - 问题ID
 */
const toReply = id => {
  router.push({
    path: '/heart/reply',
    query: {
      questionId: id // 仅传递必要参数
      // 如果目标页面需要初始化分页参数，可在此添加：
      // pageNum: 1,
      // pageSize: 5
    }
  });
};
/**
 * 删除问题
 * @param {number} id - 问题ID
 */
const onDel = async id => {
  try {
    await ElMessageBox.confirm('确定要删除该问题吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    delLoading.value = true;
    await axios.delete(`/question/delete/${id}`);

    ElMessage.success('删除成功');
    await getList(); // 等待列表刷新
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  } finally {
    delLoading.value = false;
  }
};

/**
 * 分页大小变化处理
 * @param {number} val - 每页条数
 */
const handleSizeChange = (val) => {
  formInline.pageSize = val;
  formInline.pageNum = 1;
  getList();
};

/**
 * 当前页码变化处理
 * @param {number} val - 当前页码
 */
const handleCurrentChange = (val) => {
  formInline.pageNum = val;
  getList();
};

/**
 * 获取问题列表数据
 */
const getList = async () => {
  try {
    const res = await axios.post('/question/select', formInline);
    total.value = res.data.data.total;
    tableData.value = res.data.data.list;
  } catch (error) {
    console.error('获取列表失败:', error);
    ElMessage.error('获取数据失败，请稍后重试');
  }
};
</script>

<template>
  <!-- 搜索区域 -->
  <div class="search-container">
    <el-form :inline="true" :model="formInline">
      <el-form-item label="标题">
        <el-input
            v-model="formInline.title"
            placeholder="输入问题标题"
            clearable
            @keyup.enter="getList"
        />
      </el-form-item>
      <el-form-item>
        <el-button
            type="success"
            :icon="Search"
            @click="getList"
        >
          查询
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 数据表格 -->
  <div class="table-container">
    <el-table
        :data="tableData"
        stripe
        border
        v-loading="delLoading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" fixed />
      <el-table-column prop="title" label="标题" width="200" />
      <el-table-column prop="content" label="内容" width="200" />
      <el-table-column prop="userNickname" label="用户" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="200" />

      <el-table-column label="操作" fixed="right" width="220">
        <template #default="{ row }">
          <div class="text-action-buttons">
            <el-button
                type="text"
                class="action-link"
                @click="toReply(row.id)"
            >
              <span class="text-primary">查看回复</span>
            </el-button>

            <el-button
                type="text"
                class="action-link"
                :loading="delLoading"
                @click="onDel(row.id)"
            >
              <span class="text-danger">删除</span>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        class="pagination"
        v-model:current-page="formInline.pageNum"
        v-model:page-size="formInline.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<style scoped>
.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,.1);
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,.1);
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-table {
  margin-top: 10px;
}
/* 文字按钮样式 */
.text-action-buttons {
  display: flex;
  gap: 12px; /* 按钮间距 */
}

.action-link {
  padding: 0 4px;
  :deep(.el-button__content) {
    padding: 0;
  }
}

/* 颜色定义 */
.text-primary { color: #409eff; }
.text-danger  { color: #f56c6c; }
.text-success { color: #67c23a; }

/* 鼠标悬停效果 */
.action-link:hover {
  .text-primary { color: #79bbff; text-decoration: underline; }
  .text-danger  { color: #ff7878; text-decoration: underline; }
  .text-success { color: #95d475; text-decoration: underline; }
}

/* 禁用状态 */
.is-disabled {
  .text-primary, .text-danger, .text-success {
    color: #c0c4cc;
    cursor: not-allowed;
  }
}
</style>